package main.java.org.service.serviceImpl;

import lombok.extern.slf4j.Slf4j;
import main.java.Exam.pojo.Entity.User;
import main.java.Exam.pojo.tableDTO.UserDTO;
import main.java.Exam.pojo.tableVO.UserVO;
import main.java.org.mapper.UserMapper;
import main.java.org.result.Result;
import main.java.org.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class UserserviceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;  // ，操作tb_user表

    @Override
    public UserVO login(UserDTO userDTO) {
        // 查询未删除的用户（is_deleted=0）
        User user = userMapper.selectByUsername(userDTO.getUsername());
        //判断用户是否存在
        if (user == null) {
            throw new IllegalArgumentException("用户名不存在"); // 抛异常，全局处理器捕获
        }

        //校验账号状态（必须是启用状态：status=1）
        if (user.getStatus() != 1) {
            throw new IllegalArgumentException("账号已被禁用，请联系管理员");
        }

        // 密码比对
        if (!userDTO.getPassword().equals(user.getPassword())) {
            throw new IllegalArgumentException("密码错误");
        }

        //封装返回VO（包含角色信息，供前端区分界面）
        UserVO userVO = new UserVO();
        userVO.setUsername(user.getUsername());
        userVO.setRealName(user.getRealName());
        userVO.setRoleId(user.getRoleId());


        log.info("用户[{}]登录成功，角色：{}", user.getUsername(), userVO.getRoleId());
        return userVO;
    }

    @Override
    public void register(UserDTO userDTO) {
        // 校验用户名是否已存在
        User User1 = userMapper.selectByUsername(userDTO.getUsername());
        if (User1 != null) {
            throw new IllegalArgumentException("用户名已存在");
        }

        //校验手机号是否已存在
        User Phone = userMapper.selectByPhone(userDTO.getPhone());
        if (Phone != null) {
            throw new IllegalArgumentException("手机号已被注册");
        }

        //校验角色ID合法性（1=学生、2=老师、3=管理员）
        if (userDTO.getRoleId() == null || (userDTO.getRoleId() != 1 && userDTO.getRoleId() != 2 && userDTO.getRoleId() != 3)) {
            throw new IllegalArgumentException("角色ID不合法");
        }
        //获取密码
        String userPassword = userDTO.getPassword();
        //获取姓名
        String name1 =userDTO.getRealName();


        //转换DTO为实体类
        User user = new User();
        BeanUtils.copyProperties(userDTO, user); // 复制共同字段
        user.setPassword(userPassword); // 密码
        user.setIsDeleted(0); // 默认未删除
        user.setStatus(userDTO.getStatus() == null ? 1 : userDTO.getStatus()); // 默认启用
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setRealName(name1);
        //保存用户到数据库
        userMapper.insert(user);
        log.info("用户[{}]注册成功", user.getUsername());




    }
}
